package com.xinghai.web.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.core.redis.RedisCache;
import com.xinghai.common.exception.ServiceException;
import com.xinghai.common.utils.SecurityUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.common.utils.VerifyUtil;
import com.xinghai.common.utils.bean.BeanUtils;
import com.xinghai.common.utils.uuid.IdUtils;
import com.xinghai.system.domain.QdOrder;
import com.xinghai.system.domain.QdUser;
import com.xinghai.system.domain.QdUserLink;
import com.xinghai.system.domain.entity.LoginDTO;
import com.xinghai.system.domain.entity.LoginResponse;
import com.xinghai.system.domain.entity.RegisterDTO;
import com.xinghai.system.domain.entity.RemoveDTO;
import com.xinghai.system.service.IQdOrderService;
import com.xinghai.system.service.IQdUserLinkService;
import com.xinghai.system.service.IQdUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "登录注册接口")
@RestController
@RequestMapping("/api/login")
@Slf4j
public class ApiLoginController extends BaseController {

    @Autowired
    private IQdUserService userService;

    @Autowired
    private IQdUserLinkService userLinkService;

    @Autowired
    private IQdOrderService orderService;


    /**
     * 正常注册接口
     */
    @ApiOperation("注册接口")
    @PostMapping("/register")
    public AjaxResult register(@Validated @RequestBody RegisterDTO register)
    {
        register.setPassword(SecurityUtils.encryptPassword(register.getPassword()));
        if (!VerifyUtil.phoneNumber(register.getUserPhone())){
            return error("手机号格式错误");
        }
        if (StringUtils.isBlank(register.getInviteCode())){
            throw new ServiceException("邀请码无效，请填写邀请码或者扫码注册！");
        }
        //插入注册登陆表
        if (userService.getByUserPhone(register.getUserPhone())!=null){
            return error("手机号已经注册");
        }
        //有token 就踢掉 重新存
        if(StringUtils.isNotEmpty(StpUtil.getLoginId(""))){
            StpUtil.logout();
        }
        return success(userService.registerUser(register));
    }

    /**
     * 绑定账号
     */
    @PostMapping("/binding")
    public AjaxResult binding(@Validated @RequestBody LoginDTO login)
    {
        //String loginId = StpUtil.getLoginId("");
        //创建空类接收
        //绑定人
        QdUser qdUser = null;
        //判断账号是否是手机号
        if (VerifyUtil.phoneNumber(login.getUserPhone())){
            //根据手机号获取用户信息
            log.info("手机号绑定{}",login.getUserPhone());
            //绑定人
            qdUser = userService.getByUserPhone(login.getUserPhone());
        }
        if (StringUtils.isBlank(login.getUserId())){
            return error("参数错误");
        }
        if(qdUser == null){
            log.info("该账号不存在{}",login.getUserId());
            return error("该账号不存在或密码错误");
        }
        if(!SecurityUtils.matchesPassword(login.getPassword(),qdUser.getPassword())){
            System.out.println("账号或密码错误");
            return error("该账号不存在或密码错误");
        }
        if (login.getUserId().equals(String.valueOf(qdUser.getId()))){
            return error("不能绑定主账号");
        }
        QdUserLink qdUserLink = new QdUserLink();
        qdUserLink.setUserId(Long.valueOf(login.getUserId()));
        qdUserLink.setLinkUserId(qdUser.getId());
        try {
            if ("2".equals(login.getType())){
                List<QdUserLink> list = new ArrayList<>();
                list.add(qdUserLink);
                QdUserLink qdUserLink1 = new QdUserLink();
                qdUserLink1.setUserId(qdUser.getId());
                qdUserLink1.setLinkUserId(Long.valueOf(login.getUserId()));
                list.add(qdUserLink1);
                userLinkService.saveOrUpdateBatch(list);
            }else {
                userLinkService.saveOrUpdate(qdUserLink);
            }
        }catch (Exception e){
            return error("账号已绑定");
        }
        return success();
    }

    /**
     * 绑定账号
     */
    @PostMapping("/remove")
    public AjaxResult remove(@Validated @RequestBody RemoveDTO removeDTO)
    {
        QueryWrapper<QdUserLink> queryWrapper = new QueryWrapper<>();
        if (removeDTO.getUserId().equals(removeDTO.getLinkUserId())){
            return error("不能删除主账号");
        }
        String loginId = StpUtil.getLoginId("");
        if (loginId.equals(removeDTO.getLinkUserId())){
            return error("不能删除当前登录账号");
        }
        queryWrapper.eq("user_id",removeDTO.getUserId());
        queryWrapper.eq("link_user_id",removeDTO.getLinkUserId());
        return success(userLinkService.remove(queryWrapper));
    }


    /**
     * 正常登录接口
     */
    @ApiOperation("登录接口")
    @PostMapping("/login")
    public AjaxResult login(@Validated @RequestBody LoginDTO loginDTO)
    {
        //创建空类接收
        QdUser user = null;
        //判断账号是否是手机号
        if (VerifyUtil.phoneNumber(loginDTO.getUserPhone())){
            //根据手机号获取用户信息
            log.info("手机号登录{}",loginDTO.getUserPhone());
            user = userService.getByUserPhone(loginDTO.getUserPhone());
        }
        if(user == null){
            log.info("该账号不存在{}",loginDTO.getUserPhone());
            return error("该账号不存在或密码错误");
        }
        if (StringUtils.isBlank(loginDTO.getPassword())){
            System.out.println("账号或密码错误");
            return error("该账号不存在或密码错误");
        }
        if(!SecurityUtils.matchesPassword(loginDTO.getPassword(),user.getPassword())){
            System.out.println("账号或密码错误");
            return error("该账号不存在或密码错误");
        }
        if (!"0".equals(user.getStatus())||"1".equals(user.getDelFlag())){
            return error("账号状态异常无法登录");
        }
        StpUtil.login(user.getId());
        return success(new LoginResponse(user,StpUtil.getTokenValue()));
    }

    /**
     * 正常登录接口
     */
    @ApiOperation("登录接口")
    @PostMapping("/loginById")
    public AjaxResult loginById(@RequestBody LoginDTO loginDTO)
    {
        //创建空类接收
        QdUser login = null;
        if (StringUtils.isEmpty(loginDTO.getUserId())){
            return error("登录失败");
        }
        login = userService.getById(loginDTO.getUserId());
        if(login == null){
            log.info("该账号不存在{}",loginDTO.getUserId());
            return error("该账号不存在或密码错误");
        }
        if (!"0".equals(login.getStatus())||"1".equals(login.getDelFlag())){
            return error("账号状态异常无法登录");
        }
        StpUtil.login(login.getId());
        return success(new LoginResponse(login,StpUtil.getTokenValue()));
    }

    /**
     * 正常登录接口
     */
    @PostMapping("/queryUserList")
    public AjaxResult queryUserList(@RequestBody LoginDTO loginDTO)
    {
        //创建空类接收
        QdUser login = null;
        if (StringUtils.isEmpty(loginDTO.getUserId())){
            return error("查询失败");
        }
        login = userService.getById(loginDTO.getUserId());
        if(login == null){
            log.info("该账号不存在{}",loginDTO.getUserId());
            return error("该账号不存在或密码错误");
        }
        QdUserLink userLink = new QdUserLink();
        userLink.setUserId(Long.valueOf(loginDTO.getUserId()));
        List<QdUserLink> list = userLinkService.list(userLink);
        QdUser user = new QdUser();
        user.setUserIds(list.stream().map(m->String.valueOf(m.getLinkUserId())).collect(Collectors.joining(",")));
        List<QdUser> userList = userService.list(user);
        QueryWrapper<QdOrder> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("store_id",login.getAscriptionStore());
        queryWrapper.eq("status","0");
        queryWrapper.and(m->m.apply("FIND_IN_SET(seller_user_id,'"+user.getUserIds()+"')").or().apply("FIND_IN_SET(buyer_user_id,'"+user.getUserIds()+"')"));
        List<QdOrder> list1 = orderService.list(queryWrapper);
        QdUser finalLogin = login;
        List<QdUserLink> userLinkList = userList.stream().map(m -> {
            QdUserLink link = new QdUserLink();
            link.setLinkUserId(m.getId());
            link.setUserId(finalLogin.getId());
            link.setAvatar(m.getAvatar());
            link.setNickName(m.getNickName());
            link.setUserPhone(m.getUserPhone());
            List<QdOrder> orderList = list1.stream().filter(n -> n.getSellerUserId().equals(m.getId())).collect(Collectors.toList());
            if (orderList.isEmpty()){
                link.setSkOrder("0");
                link.setFkOrder("0");
                link.setSjOrder("0");
            }else {
                link.setSkOrder(String.valueOf(orderList.stream().filter(n -> "1".equals(n.getBuyerStatus())).count()));
                link.setFkOrder(String.valueOf(orderList.stream().filter(n -> "0".equals(n.getSellerStatus())).count()));
                link.setSjOrder(String.valueOf(orderList.stream().filter(n -> "2".equals(n.getSellerStatus())).count()));
            }
            return link;
        }).collect(Collectors.toList());
        return success(userLinkList);
    }

    /**
     * 正常退出接口
     */
    @PostMapping("/logout")
    public AjaxResult logout()
    {
        //有token 就踢掉 重新存
        if(StringUtils.isNotEmpty(StpUtil.getLoginId(""))){
            StpUtil.logout();
        }
        return success();
    }

}
